<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;

class PermissionsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = Permission::paginate();

        return view('permissions.index', compact('list'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $info = null;

        return view('permissions.create_and_edit', compact('info'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $this->validate($request, [
            'name' => 'required',
            'desc_name' => 'required',
        ], [
            'name.required' => '请输入权限名称',
            'desc_name.required' => '请输入权限别名',
        ]);

        if (Permission::create($data)) {
            return redirect()->route('permissions.index')->with('success', '新增成功');
        } else {
            return redirect()->route('permissions.index')->with('danger', '新增失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $info = Permission::find($id);

        return view('permissions.create_and_edit', compact('info'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $this->validate($request, [
            'desc_name' => 'required',
        ], [
            'desc_name.required' => '请输入权限别名',
        ]);

        if (Permission::where('id', $id)->update($data)) {
            return redirect()->route('permissions.index')->with('success', '编辑成功');
        } else {
            return redirect()->route('permissions.index')->with('danger', '编辑失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (Permission::destroy($id)) {
            return back()->with('success', '删除成功');
        } else {
            return back()->with('danger', '删除失败 ');
        }
    }
}
